package org.gitos.cloud.background.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.gitos.cloud.cmd.controller.BaseController;
import org.gitos.cloud.domain.exception.NotificationException;
import org.gitos.cloud.domain.rpc.BRomRPC;
import org.gitos.cloud.domain.server.Rom;
import org.gitos.cloud.util.Pagination;
import org.gitos.cloud.util.WebKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.annotation.Reference;

@Controller
public class BRomController extends BaseController {
	private static final Logger log = LoggerFactory.getLogger(BRomController.class);

	@Value("${rom.storage}")
	private String romStorage;

	@Reference
	private BRomRPC bRomRPC;

	@RequestMapping(value = "/background/rom/addRom", method = RequestMethod.POST)
	public String addRom(HttpServletRequest request, String name, @RequestParam("file") MultipartFile file, @RequestParam("version") String version,
			@RequestParam(name = "type") int type) throws IllegalStateException, IOException {
		String romType = "";
		switch (type) {
		case 1:
			romType = "wifi";
			break;
		case 2:
			romType = "mcu";
			break;
		default:
			throw new NotificationException("类型错误！");
		}
		String originalFilename = file.getOriginalFilename();
		File path = new File(romStorage + "/" + romType + "/");
		if (!path.exists()) {
			path.mkdirs();
		}
		File rom = new File(path.getPath() + "/" + originalFilename);
		file.transferTo(rom);
		String url = WebKit.getContextPath(request) + "/rom/" + romType + "/" + originalFilename;
		System.out.println(request.getRemoteHost());
		System.out.println(request.getServletPath());
		bRomRPC.addRom(name, version, type, url);
		return "index";
	}

	@RequestMapping("/background/rom/index")
	public String index() {
		return "index";
	}

	@RequestMapping("/background/rom/addRomWeb")
	public String addRomWeb() {
		return "addRom";
	}

	@RequestMapping("/background/rom/list")
	@ResponseBody
	public Pagination<Rom> list(@RequestParam("pageNumber") int pageNumber, @RequestParam("pageSize") int pageSize, @RequestParam("type") int type,
			String sortName, String sortOrder) {
		return bRomRPC.list(pageNumber, pageSize, type, sortName, sortOrder);
	}
}
